import {reactive} from "../reactivity/index.js";

export function initProps(instance, rawProps) {
    const props = {}
    const attrs = {}
    const options = instance.propsOptions || {}
    if (rawProps) {
        for (const key in rawProps) {
            if (key in options) {
                props[key] = rawProps[key]
            } else {
                attrs[key] = rawProps[key]
            }
        }
    }
    instance.props = reactive(props) // 属性会被变成响应式，源码里边用的shadowReactive，只做第一层的响应式
    instance.attrs = attrs
}


export function hasChangedProps(prevProps, nextProps) {
    const nextKeys = Object.keys(nextProps)
    const prevKeys = Object.keys(prevProps)
    if (nextKeys.length !== prevKeys.length) {
        return true
    }
    for (let i = 0; i < nextKeys.length; i++) {
        const key = nextKeys[i]
        if (nextProps[key] !== prevProps[key]) {
            return true
        }
    }
    return false
}

export function updateProps(prevProps, nextProps) {
    // 组件自己不能更新属性，但是在父组件可以更新属性（原本的props就是proxy）
    for (const key in nextProps) {
        // instance.props = nextProps // 丧失响应式，必须修改内部属性触发更新
        prevProps[key] = nextProps[key]
    }
    for (const key in prevProps) {
        if (!(key in nextProps)) {
            delete prevProps[key]
        }
    }

}
